home *** CD-ROM | disk | FTP | other *** search
/ PC Plus SuperCD (UK) 1998 August / PC Plus SuperCD 50b Issue 142 (CD142b) (August 1998).iso / essent / FIXES / CSeries.exe / issue100 / CPROG11.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1994-10-31  |  1.6 KB  |  46 lines

  1. /* CPROG11.CPP - Fill a 2D array, then print its contents */
  2.  
  3. #include <stdio.h>
  4.  
  5. void main(void)
  6. {
  7. int i, j,        // Loop counters
  8.     x,            // Holds the value being put in the current array element
  9.     grid[3][2];        // The array, called grid, is 3 rows of 2
  10.             // Note how the declaration is split over several
  11.             // lines - a carriage return is not the
  12.             // end-of-declaration marker. The semi-colon is.
  13.  
  14.     // *********** Fill the array ************* //
  15.     for(i=0, x=1; i<3; i++)            // x=1; For each row...
  16.         for(j=0; j<2; j++)        // For each element in row...
  17.             grid[i][j]=x++;        // Insert x and increment it
  18.  
  19.     /* This uses a nested loop. The outer one, controlled by counter i,
  20.     causes each row to be processed in turn. The inner loop runs along
  21.     each row, putting the current value of x into the current element.
  22.     There is no need to put the second two lines in braces. The outer
  23.     loop executes the single statment after it (the j loop). That in turn
  24.     executes the single statement after it.
  25.     The first element in the for(i=0, x=1;... line is quite legal - you
  26.     can have multiple statements, separated by commas, before the first
  27.     semicolon. The same applies to the third element. */
  28.  
  29.  
  30.  
  31.     // ********** Print the array ************* //
  32.  
  33.     putchar('\n');              // Make sure we're on a new line
  34.  
  35.     for(i=0; i<3; i++)
  36.         {
  37.         for(j=0; j<2; j++)
  38.             printf("%d ", grid[i][j]);
  39.         putchar('\n');
  40.         }
  41.     /* This needs braces because there is more than one instruction to
  42.     be executed for each iteration of the outer loop. When the j loop
  43.     has processed a line, we print a newline character to start a new
  44.     screen line. */
  45. }
  46.